package com.zryc.shop.oms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zryc.shop.client.IAdminServiceClient;
import com.zryc.shop.oms.entity.Order;
import com.zryc.shop.oms.entity.OrderOperateHistory;
import com.zryc.shop.oms.service.IOrderOperateHistoryService;
import com.zryc.shop.oms.service.IOrderService;
import com.zryc.shop.ums.entity.Admin;
import com.zryc.shop.util.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author 王志平
 * @since 2024-10-01
 */
@RestController
@RequestMapping("/oms/order")
@Api(tags = "订单管理接口列表")
public class OrderController {
    @Autowired
    private IOrderService orderService;

    @GetMapping("/list")
    @ApiOperation("分页查询列表")
    public ResponseResult list(@RequestParam(defaultValue = "1") @ApiParam(value = "页码", required = true) Integer pageNum,
                               @RequestParam(defaultValue = "10") @ApiParam(value = "每页显示条数", required = true) Integer pageSize,
                               @RequestParam(required = false) @ApiParam("订单编号") String orderSn,
                               @RequestParam(required = false) @ApiParam("收货人信息：姓名/电话") String receiverKeyword,
                               @RequestParam(required = false) @ApiParam("订单状态") Integer status,
                               @RequestParam(required = false) @ApiParam("订单类型：正常/秒杀") Integer orderType,
                               @RequestParam(required = false) @ApiParam("订单来源：PC/App") Integer sourceType,
                               @RequestParam(required = false) @ApiParam("订单发起日期") @DateTimeFormat(pattern = "yyyy-MM-dd") Date createTime) {
        Page page = new Page(pageNum, pageSize);
        QueryWrapper queryWrapper = new QueryWrapper();
        if (!StringUtils.isEmpty(orderSn)) {
            queryWrapper.eq("order_sn", orderSn);
        } else {
            if (!StringUtils.isEmpty(receiverKeyword)) {
                queryWrapper.eq("receiver_name", receiverKeyword);
            }
            if (status != null) {
                queryWrapper.eq("status", status);
            }
            if (orderType != null) {
                queryWrapper.eq("order_type", orderType);
            }
            if (sourceType != null) {
                queryWrapper.eq("source_type", sourceType);
            }
            if (createTime != null) {
                // Calendar
                LocalDateTime t1 = LocalDateTime.of(createTime.getYear() + 1900, createTime.getMonth() + 1, createTime.getDate(), 0, 0, 0);
                LocalDateTime t2 = t1.plusDays(1);//加上一天（第二天）
                queryWrapper.between("create_time", t1, t2);
            }
        }
        queryWrapper.eq("delete_status", 0);//不查询已删除订单
        //queryWrapper.ne("delete_status", 1);//不查询已删除订单
        orderService.page(page, queryWrapper);
        return new ResponseResult(200, "查询完成", page);
    }

    @PostMapping("/delete")
    @ApiOperation("删除订单")
    @Transactional
    public ResponseResult delete(@RequestParam String ids, @RequestHeader("Authorization") String token) {
        String[] idArr = ids.split(",");
        for (String orderId:idArr) {
            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.eq("id", orderId);
            updateWrapper.in("status", new Integer[]{4, 5});//只有已关闭订单和无效订单可以被删除
//            updateWrapper.in("status", Arrays.asList(4,5));
            updateWrapper.set("delete_status", 1);
            updateWrapper.set("modify_time", LocalDateTime.now());//更新订单的最后修改时间
            boolean flag = orderService.update(updateWrapper);
            Admin admin = adminServiceClient.briefInfo(token).getData();
            if (flag) {//当上一行的flag==true，说明删除操作成功
                //添加操作日志记录
                OrderOperateHistory history = new OrderOperateHistory(null, Long.valueOf(orderId), admin.getNickName(),
                        LocalDateTime.now(), 4, "删除订单！");
                operateHistoryService.save(history);
            }
        }
        return new ResponseResult(200, "删除成功");
    }

    @Autowired
    private IOrderOperateHistoryService operateHistoryService;//操作订单管理日志表的业务代码
    @Autowired
    private IAdminServiceClient adminServiceClient;

    @PostMapping("/update/close")
    @ApiOperation("关闭订单")
    @Transactional
    public ResponseResult close(@RequestParam @ApiParam("订单ID列表") String ids,
                                @RequestParam @ApiParam("操作日志备注") String note,
                                @RequestHeader("Authorization") String token) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.select("id", "status");
        queryWrapper.in("id", ids.split(","));
        //订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
        queryWrapper.eq("status", 0);//只查询服务关闭条件的（未付款）的订单
        List<Order> orderList = orderService.list(queryWrapper);
        for (Order order:orderList) {
            order.setStatus(4);//将订单状态改为已关闭
            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.eq("id", order.getId());
            updateWrapper.set("status", order.getStatus());
            updateWrapper.set("modify_time", LocalDateTime.now());//更新订单的最后修改时间
            orderService.update(updateWrapper);
            //在日志表中记录这一操作
            OrderOperateHistory history = new OrderOperateHistory();
            history.setCreateTime(LocalDateTime.now());
            history.setOrderId(order.getId());
            history.setOrderStatus(order.getStatus());
            history.setNote("关闭订单：" + note);
            Admin admin = adminServiceClient.briefInfo(token).getData();
            history.setOperateMan(admin.getUsername() + "/" + admin.getNickName());//管理员姓名或昵称
            operateHistoryService.save(history);
        }
        return new ResponseResult(200, "修改成功");
    }

    @GetMapping("/{id}")
    @ApiOperation("查询订单详情")
    public ResponseResult info(@PathVariable Long id) {
        return new ResponseResult(200, "查询完成", orderService.getById(id));
    }

    @PostMapping("/update/receiverInfo")
    @ApiOperation("修改收件人信息")
    @Transactional
    public ResponseResult updateReceiverInfo(@RequestBody HashMap params, @RequestHeader("Authorization") String token) {//将请求体中的JSON反序列化成一个Map
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id", params.get("orderId"));
        updateWrapper.set("receiver_name", params.get("receiverName"));
        updateWrapper.set("receiver_phone", params.get("receiverPhone"));
        updateWrapper.set("receiver_post_code", params.get("receiverPostCode"));
        updateWrapper.set("receiver_detail_address", params.get("receiverDetailAddress"));
        updateWrapper.set("receiver_province", params.get("receiverProvince"));
        updateWrapper.set("receiver_city", params.get("receiverCity"));
        updateWrapper.set("receiver_region", params.get("receiverRegion"));
        updateWrapper.set("modify_time", LocalDateTime.now());
        orderService.update(updateWrapper);
        //在日志表中记录这一操作
        OrderOperateHistory history = new OrderOperateHistory();
        history.setCreateTime(LocalDateTime.now());
        history.setOrderId(Long.valueOf(params.get("orderId").toString()));
        history.setOrderStatus((Integer) params.get("status"));
        history.setNote("修改收件人地址！");
        Admin admin = adminServiceClient.briefInfo(token).getData();
        history.setOperateMan(admin.getUsername() + "/" + admin.getNickName());//管理员姓名或昵称
        operateHistoryService.save(history);
        return new ResponseResult(200, "修改成功");
    }
//{
//  "orderId": 29,
//  "freightAmount": 10,
//  "discountAmount": 20,
//  "status": 0
//}
    @PostMapping("/update/moneyInfo")
    @ApiOperation("修改订单费用信息")
    @Transactional
    public ResponseResult updateMoneyInfo(@RequestBody HashMap params, @RequestHeader("Authorization") String token) {
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id", params.get("orderId"));
        updateWrapper.set("freight_amount", params.get("freightAmount"));
        updateWrapper.set("discount_amount", params.get("discountAmount"));
        updateWrapper.set("modify_time", LocalDateTime.now());
        orderService.update(updateWrapper);
        //在日志表中记录这一操作
        OrderOperateHistory history = new OrderOperateHistory();
        history.setCreateTime(LocalDateTime.now());
        history.setOrderId(Long.valueOf(params.get("orderId").toString()));
        history.setOrderStatus((Integer) params.get("status"));
        history.setNote("修改订单费用信息！");
        Admin admin = adminServiceClient.briefInfo(token).getData();
        history.setOperateMan(admin.getUsername() + "/" + admin.getNickName());//管理员姓名或昵称
        operateHistoryService.save(history);
        return new ResponseResult(200, "修改成功");
    }

    @PostMapping("/update/note")
    @ApiOperation("修改备注信息")
    @Transactional
    public ResponseResult updateNote(@RequestParam @ApiParam(value = "订单ID", required = true) Long id,
                                     @RequestParam @ApiParam(value = "订单状态", required = true) Integer status,
                                     @RequestParam @ApiParam(value = "订单备注", required = true) String note,
                                     @RequestHeader("Authorization") String token) {
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id", id);
        updateWrapper.set("note", note);
        updateWrapper.set("modify_time", LocalDateTime.now());
        orderService.update(updateWrapper);
        //在日志表中记录这一操作
        OrderOperateHistory history = new OrderOperateHistory();
        history.setCreateTime(LocalDateTime.now());
        history.setOrderId(id);
        history.setOrderStatus(status);
        history.setNote("修改备注：" + note);
        Admin admin = adminServiceClient.briefInfo(token).getData();
        history.setOperateMan(admin.getUsername() + "/" + admin.getNickName());//管理员姓名或昵称
        operateHistoryService.save(history);
        return new ResponseResult(200, "修改成功");
    }

    @PostMapping("/update/delivery")
    @ApiOperation("订单发货")
    public ResponseResult delivery(@RequestBody List<HashMap> params, @RequestHeader("Authorization") String token) {
        for (HashMap param:params) {
            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.eq("id", param.get("orderId"));
            updateWrapper.set("delivery_company", param.get("deliveryCompany"));
            updateWrapper.set("delivery_sn", param.get("deliverySn"));
            updateWrapper.set("modify_time", LocalDateTime.now());
            //订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
            updateWrapper.set("status", 2);
            orderService.update(updateWrapper);
            //在日志表中记录这一操作
            OrderOperateHistory history = new OrderOperateHistory();
            history.setCreateTime(LocalDateTime.now());
            Long orderId = Long.valueOf(param.get("orderId").toString());
            history.setOrderId(orderId);
            history.setOrderStatus(2);
            history.setNote("订单发货！");
            Admin admin = adminServiceClient.briefInfo(token).getData();
            history.setOperateMan(admin.getUsername() + "/" + admin.getNickName());//管理员姓名或昵称
            operateHistoryService.save(history);
        }
        return new ResponseResult(200, "修改成功");
    }
}
